<template>
  <div class="login-container">
    <div class="login-left">
      <img src="@/assets/login-left.svg" alt="login" class="login-illustration">
    </div>
    <div class="login-content">
      <h2 class="login-title">PROPERY</h2>
      <p class="login-subtitle">欢迎来到使用智慧家园物业SAAS管理平台</p>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            :prefix-icon="User"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="captcha">
          <div class="captcha-wrapper">
            <el-input
              v-model="loginForm.captcha"
              placeholder="验证码"
              :prefix-icon="Key"
              @keyup.enter="handleLogin"
            />
            <img 
              :src="captchaUrl" 
              alt="captcha" 
              class="captcha-img"
              @click="refreshCaptcha"
            >
          </div>
        </el-form-item>

        <el-button
          :loading="loading"
          type="primary"
          class="login-button"
          @click="handleLogin"
        >
          登 录
        </el-button>

        <!-- <div class="login-options">
          <el-link type="primary">注册</el-link>
        </div> -->
      </el-form>

      <div class="login-footer">
        <p>Copyright © 2025 Vue Admin Plus</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { login } from '@/api'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref(null)

const loginForm = ref({
  username: 'admin',
  password: '123456',
  captcha: ''
})

// 生成随机验证码
const captchaText = ref('')
const captchaCanvas = ref(null)

// 生成随机颜色
const randomColor = (min, max) => {
  const r = Math.floor(Math.random() * (max - min + 1) + min)
  const g = Math.floor(Math.random() * (max - min + 1) + min)
  const b = Math.floor(Math.random() * (max - min + 1) + min)
  return `rgb(${r},${g},${b})`
}

// 生成随机验证码
const createCaptcha = () => {
  const canvas = document.createElement('canvas')
  canvas.width = 100
  canvas.height = 40
  const ctx = canvas.getContext('2d')
  
  // 填充背景色
  ctx.fillStyle = '#f5f5f5'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 生成4位随机验证码
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let code = ''
  for (let i = 0; i < 4; i++) {
    const char = chars[Math.floor(Math.random() * chars.length)]
    code += char
    
    // 随机字体大小
    const fontSize = Math.random() * 10 + 20
    ctx.font = `${fontSize}px Arial`
    ctx.textBaseline = 'middle'
    
    // 随机旋转角度
    const rotate = (Math.random() - 0.5) * 0.3
    ctx.translate(25 * i + 15, 20)
    ctx.rotate(rotate)
    
    // 随机颜色
    ctx.fillStyle = randomColor(50, 160)
    ctx.fillText(char, 0, 0)
    
    // 重置变换
    ctx.rotate(-rotate)
    ctx.translate(-(25 * i + 15), -20)
  }
  
  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = randomColor(150, 200)
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
  
  // 添加干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = randomColor(150, 200)
    ctx.beginPath()
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
    ctx.fill()
  }
  
  captchaText.value = code.toLowerCase()
  return canvas.toDataURL()
}

// 验证码图片 URL
const captchaUrl = ref('')

// 刷新验证码
const refreshCaptcha = () => {
  captchaUrl.value = createCaptcha()
}

// 验证码验证
const validateCaptcha = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入验证码'))
  } else if (value.toLowerCase() !== captchaText.value) {
    callback(new Error('验证码错误'))
  } else {
    callback()
  }
}

// 修改验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator: validateCaptcha, trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await login(loginForm.value)
        localStorage.setItem('token', res.data.token)
        ElMessage.success('登录成功')
        router.push('/')
      } catch (error) {
        console.error('登录失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 在组件挂载时生成验证码
onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  background: #4318ff;
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background: url('@/assets/login-bg.jpg') no-repeat;
  background-size: cover;
  
}

.login-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.login-illustration {
  max-width: 600px;
  width: 100%;
  height: auto;
}

.login-content {
  width: 450px;
  padding: 67px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  margin: 150px 240px 150px 0;
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
}

.login-title {
  font-size: 36px;
  font-weight: bold;
  color: #2B3674;
  margin-bottom: 8px;
}

.login-subtitle {
  font-size: 16px;
  color: #707EAE;
  margin-bottom: 40px;
}

.captcha-wrapper {
  display: flex;
  align-items: center;
  position: relative;
}

.captcha-img {
  position: absolute;
  right: 1px;
  top: 1px;
  height: 42px;
  width: 120px;
  border-radius: 0 16px 16px 0;
  cursor: pointer;
  background: #fff;
}

/* 添加提示 */
.captcha-img:hover::after {
  content: '点击刷新';
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #909399;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  margin-top: 20px;
  background: #4318FF;
  border: none;
  border-radius: 16px;
}

.login-button:hover {
  background: #3311dd;
}

.login-options {
  margin-top: 16px;
  text-align: center;
}

.login-footer {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  color: #707EAE;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  height: 44px;
}

:deep(.el-input__inner) {
  height: 42px;
}

/* 处理谷歌浏览器自动填充样式 */
:deep(.el-input__inner:-webkit-autofill) {
  -webkit-box-shadow: 0 0 0 1000px rgba(255, 255, 255, 0.8) inset;
  -webkit-text-fill-color: #606266;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

/* 验证码输入框特殊处理 */
.captcha-wrapper :deep(.el-input__wrapper) {
  padding-right: 120px;
}

@media (max-width: 1200px) {
  .login-left {
    display: none;
  }
  
  .login-content {
    width: 100%;
    margin: 20px;
  }
}
</style>